package com.desuntech.utils
{
	import C4D.kbmMWConnection;
	import C4D.kbmMWQuery;
	
	import mx.controls.Alert;

	public class UniqueCheck
	{
		private var _conn:kbmMWConnection;
		private var _resultHandler:Function;
		private var _q:kbmMWQuery;
		
		public function UniqueCheck(conn:kbmMWConnection)
		{
			_conn = conn;
		}
		
		public function checkUnique(table:String, resultHandler:Function, rows:Array):void
		{
			var sql:String = 'SELECT COUNT(*) as XCOUNT FROM ' + table + ' WHERE ';
			for(var i:int = 0;i<rows.length;i++) {
				if(i) sql += ' AND ';
				sql += rows[i]['name'] + ' = ';
				if(rows[i]['value'] is String) sql += '\'' + rows[i]['value'] + '\'';
				if(rows[i]['value'] is int) sql += rows[i]['value'];
			}
			_resultHandler = resultHandler;
			_q = new kbmMWQuery();
			_q.Connection = _conn;
			_q.Query = sql;
			_q.Open(checkSuccess, checkFailed);
		}
		
		private function checkSuccess(o:Object):void {
			var totalCount:int = _q[0]['XCOUNT'];
			_resultHandler(totalCount?false:true);
		}
		
		private function checkFailed(o:Object):void {
			Alert.show(o.toString(), '操作失败');
		}
	}
}